import time

from fastapi import FastAPI, Depends, Request

from .config import app_setting
from .api import router
from .dependency import auth
from .resource_model.drive_115.dependency import prepare_db, close_client, refresh_115_cache
from .resource_model.drive_115.data_operate import notfound_handler, ResNotFound


def create_app() -> FastAPI:
    app = FastAPI(
        title="webdav_server", dependencies=[Depends(auth)], openapi_url=None, redoc_url=None
    )
    app.include_router(router)
    app.add_exception_handler(ResNotFound, notfound_handler)

    if app_setting.ENABLE_TEST_API:
        from .api_dev import router as dev_router
        app.include_router(dev_router)

    @app.middleware("http")
    async def add_process_time_header(request: Request, call_next):
        start_time = time.time()
        response = await call_next(request)
        process_time = time.time() - start_time
        response.headers["X-Process-Time"] = f"{str(round(process_time * 1000))}ms"
        return response

    @app.on_event('startup')
    async def before_start():
        await prepare_db()
        await refresh_115_cache()

    @app.on_event("shutdown")
    async def shutdown():
        await close_client()

    return app


webdav_app = create_app()
